package cn.laixueit.task;

import cn.laixueit.CacheKey;
import cn.laixueit.crawlerutil.CrawlerUtil;
import cn.laixueit.pojo.Book;
import cn.laixueit.pojo.Chapter;
import cn.laixueit.service.BookService;
import cn.laixueit.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import sun.misc.Cache;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class CrawlerBook {

    @Autowired
    BookService bookService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private RedisTemplate redisTemplate;


    @Scheduled(cron = "* * 1 * * ?")
    public void crawlerBook(){
//        System.out.println("开始爬取小说");
        List<Map> mapList = CrawlerUtil.getBookName(CrawlerUtil.BIQUGE_URL);
        bookService.add(mapList);
        // 执行缓存任务
        bookService.cache();
    }

    @Scheduled(cron = "* 30 1 * * ?")
    public void crawlerChapter(){
        // 数据库中的所有小说
        List<Book> dbbookList = bookService.findAll(null);

        // 保存所有章节到数据库
        List<Map> mapChapterList = null;
        for (Book book : dbbookList) {
            // 爬取当前小说所有章节
            mapChapterList = CrawlerUtil.getBookChapter(book.getLinkUrl());
            //保存差集到数据库
            chapterService.add(mapChapterList,book.getId());
        }



        // 获取缓存中章节对应的书籍id
        Set<Integer> keys = redisTemplate.boundHashOps(CacheKey.CHAPTER).keys();
        for (Integer bookId : keys) {
            Book book = bookService.findByDBBookId(bookId);
            mapChapterList = CrawlerUtil.getBookChapter(book.getLinkUrl());

            List<Chapter> chapterList = (List<Chapter>) redisTemplate.boundHashOps(CacheKey.CHAPTER).get(book.getId());
            // 判断网站上的章节和redis中的章节数目一致不，不一致就删除redis中的，重新缓存
            if(mapChapterList.size()!=chapterList.size()){
                redisTemplate.boundHashOps(CacheKey.CHAPTER).delete(book.getId());
                redisTemplate.boundHashOps(CacheKey.CHAPTER).put(book.getId(),mapChapterList);
            }
        }

        // 执行缓存任务
//        chapterService.cache();

    }
}
